﻿/*
 * RegExpress
 * 
 * Copyright (c) 2010, Daniel McGaughran
 * 
 * Licensed under the Apache Licence, Version 2.0 (the "Licence");
 * you may not use this file except in compliance with the Licence.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 * 
 */

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using RegExpressModel.Entities;


namespace RegExpressModel
{
	public class BasicMatchModel : BaseRegexModel
	{
		private string _input;

        public BasicMatchModel() : base()
        {
			ResultStatus = MatchResultType.Unknown;
			MatchResult = Match.Empty;
			CapturedGroups = new List<GroupCapture>();
        }


		public string Input
		{
			get { return _input; }
			set
			{
				_input = value;
				ResetResults();
			}
		}


		public MatchResultType ResultStatus { get; protected set; }
		public Match MatchResult { get; protected set; }
		public List<GroupCapture> CapturedGroups { get; protected set; }



		public bool PerformMatch()
		{
			if(IsValid)
			{
				ResultStatus = RegexObject.IsMatch(Input) ? MatchResultType.Matches : MatchResultType.NoMatch;
				MatchResult = RegexObject.Match(Input);

				CapturedGroups.Clear();
				int[] indexes = RegexObject.GetGroupNumbers();
				foreach(int i in indexes)
				{
					GroupCapture currentGroup = new GroupCapture()
					{
						GroupNumber = i,
						GroupName = RegexObject.GroupNameFromNumber(i),
						Value = MatchResult.Groups[i].Value
					};
					CapturedGroups.Add(currentGroup);
				}

				return true;
			}

			return false;
		}



		/// <summary>
		/// Resets the results when either the input or regex object is changed.
		/// </summary>
		protected override void ResetResults()
		{
			ResultStatus = MatchResultType.Unknown;
			MatchResult = Match.Empty;
			CapturedGroups.Clear();
		}

	
	}
}
